package cameragps;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.io.Base64OutputStream;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;

/**
 * This class is DAO which allows to store images as well manage unsent images
 * 
 */
public class ImageUtils {

	static PersistentObject outbox;
	static PersistentObject account;

	/**
	 * this vector contains the information of images it stores ImageInformation
	 * Objects
	 */
	protected static Vector dataVector;
	protected static String accountString;
	public static String path = "file:///store/home/user/pictures/";

	static {
		outbox = PersistentStore.getPersistentObject(0xde71536755efb035L); // worldbank.cameragps.ql189fga2co
		account = PersistentStore.getPersistentObject(0x73ff36de14b59fafL); // worldbank.cameragps.dfowohoi
	}

	/**
	 * This method initialize the persistent Storage for unsent items
	 * information.
	 */
	public static void initPersistentStorage() {
		try {
			dataVector = (Vector) outbox.getContents();

			if (dataVector == null) {
				dataVector = new Vector();
			}
		} catch (Exception e) {
			helloBerry.errorDialog("Error in gettting unsent Image information : 51" + e);
		}

		
		//getting email a/c information
		try {
			accountString = (String) account.getContents();

			if (accountString == null) {
				accountString = "";
			}
		} catch (Exception e) {
			helloBerry.errorDialog("Error in gettting Account Information : 63 " + e);
		}
	}

	/**
	 * This method saves image in to user's pictures directory
	 * 
	 * @param imageName
	 *            image name with extension
	 * @param image
	 *            in form of raw bytes
	 */
	public static boolean saveImage(String imageName, byte[] rawImage) {
		try {
			FileConnection fileCon = (FileConnection) Connector.open(path
					+ imageName);
			// If no exception is thrown, then the URI is valid, but the file
			// may or may not exist.
			if (!fileCon.exists()) {
				fileCon.create(); // create the file if it doesn't exist
			}
			OutputStream outStream = fileCon.openOutputStream();
			outStream.write(rawImage);
			outStream.close();
			fileCon.close();

		} catch (IOException ioe) {
			helloBerry.errorDialog("Problem saving Image : 90 " + ioe);
			return false;
		}

		return true;
	}

	/**
	 * This methos reads file from user's pictures folder
	 * 
	 * @param imageName
	 *            name of file e.g. justanimage.jpg
	 * @return returns file in form of byte[]
	 */
	public static byte[] getBytesFromImage(String imageName) {

		StringBuffer redData = new StringBuffer();

		try {
			FileConnection fc = (FileConnection) Connector.open(path
					+ imageName);

			// If no exception is thrown, then the URI is valid, but the file
			// may or may not exist.
			if (!fc.exists()) {
				return null;
			}

			InputStream inStream = fc.openInputStream();
			byte[] data = new byte[256];
			int len = 0;

			while (-1 != (len = inStream.read(data))) {
				redData.append(new String(data, 0, len));
			}

			inStream.close();

			fc.close();
		} catch (IOException ioe) {
			helloBerry.errorDialog("Problem saving Image : 130" + ioe);
			return null;
		}

		return redData.toString().getBytes();
	}

	/**
	 * This method is called when Internet is not reachable so it will do the
	 * necessary procedure as well as store the image
	 * 
	 * @param email
	 *            email field to send to server
	 * @param ImageName
	 *            name fiield to send to server
	 * @param UserText
	 * @param Latitude
	 * @param Longitude
	 * @param rawImage
	 *            image in byte[] form
	 * @throws Exception
	 */
	public static boolean saveNew(String ImageName, String UserText,
			String Latitude, String Longitude, String locationAddress,
			boolean isSent, byte[] rawImage) {
		try {
			dataVector.addElement(new ImageInformation(
					new String[] { ImageName, UserText, Latitude, Longitude,
							locationAddress }, isSent));

			outbox.setContents(dataVector);
			PersistentObject.commit(dataVector);

		} catch (Exception e) {
			helloBerry.errorDialog("Not able to save information 164" + e);
		}

		saveImage(ImageName, rawImage);

		return true;

	}

	/**
	 * method to delete image as well as its information
	 * 
	 * @param FileName
	 *            name of picturefile to delete
	 * @param index
	 *            The index in dataVector
	 */
	protected static void deleteImage(String fileName, int index) {
		try {
			FileConnection fcon = (FileConnection) Connector.open(path
					+ fileName, Connector.READ_WRITE);
			if (fcon.exists()) {
				fcon.delete();
				removeInformation(index);
			} else
				Dialog.inform("file Doens not exist!");
		} catch (IOException e) {
			helloBerry.errorDialog("Unable to delete file! 191 "+ e);
		}
	}

	protected static String xmlBuilder(String[] fields, byte[] raw) {
		String encoded = null;
		
		try {
			encoded = Base64OutputStream.encodeAsString(raw, 0, raw.length,
					false, false);
		} catch (Exception e) {

		}

		String xmlMessage = "<Data DeviceID=\"" + helloBerry.dID + "\">";
		xmlMessage += "<Email>" + ImageUtils.accountString + "</Email>\"";
		xmlMessage += "<ImageName>" + fields[ImageInformation.IMAGENAME] + "</ImageName>";
		xmlMessage += "<UserText>" + fields[ImageInformation.USERTEXT]+ "</UserText>";
		xmlMessage += "<Latitude>" + fields[ImageInformation.LATITUDE]+ "</Latitude>";
		xmlMessage += "<Longitude>" + fields[ImageInformation.LONGITUDE]+ "</Longitude>";
		xmlMessage += "<ImageString>" + encoded + "</ImageString>";
		xmlMessage += "</Data>";

		return xmlMessage;

	}

	protected static void removeInformation(int index) {

		dataVector.removeElementAt(index);

		outbox.setContents(dataVector);
		PersistentObject.commit(dataVector);
	}

	protected static boolean SendHttpPost(String xmlString) {

		boolean returnValue;
//		http://devweb.wearepassionfruit.com/nallu/Submit.aspx
//		;ConnectionTimeout=15000
		
		String connectionString = "http://worldbank.thetigerparty.com/Submit.aspx";
		//String connectionString = "http://localhost:64118/webztt/Submit.aspx;deviceside=false;ConnectionTimeout=60000";
		// for 1 minute time out append ;ConnectionTimeout=60000
		String respond = null;
		int respondCode = 0;
		try {
			byte[] postDataBytes = xmlString.getBytes();
			
			ConnectionFactory connFactory = new ConnectionFactory();
			ConnectionDescriptor connDesc ;
			connDesc = connFactory.getConnection(connectionString);
			
			if(connDesc != null)
			{
			HttpConnection hconnection =  (HttpConnection)connDesc.getConnection();
			hconnection.setRequestMethod(HttpConnection.POST);
			//hconnection.setRequestProperty("User-Agent"	, "BlackBerry");
			//hconnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
			hconnection.setRequestProperty("Content-Type", "text/xml");
			hconnection.setRequestProperty("Content-Length", Integer.toString(postDataBytes.length));
			
			
			OutputStream out = hconnection.openDataOutputStream();	
			
			out.write(postDataBytes);
			out.flush();
			
			respond = hconnection.getResponseMessage();
			respondCode = hconnection.getResponseCode();
			}
			
			System.out.println("respond : " + respond + " | "
					+ "respondCode : " + respondCode);

			if (respondCode == HttpConnection.HTTP_OK)
				returnValue = true;
			else
				throw new IOException();
		} catch (IOException e) {
			returnValue = false;
		}
		return returnValue;

	}

	protected static void markAsSent(int i) {
		((ImageInformation) dataVector.elementAt(i)).markAsSent();
		outbox.setContents(dataVector);
		PersistentObject.commit(dataVector);
	}

	protected static void saveAccount(String accountStr) {
		accountString = accountStr;
		account.setContents(accountString);
		PersistentObject.commit(accountStr);
	}

//	/**
//	 * Just to wipe out image informations in perstistentStore
//	 */
//	protected static void clear() {
//		outbox.setContents(null);
//		outbox.commit();
//	}

}
